<template>
  <div class="character-editor-container">
    <n-card class="character-editor-card">
      <template #header>
        <div class="card-header">
          <h1>{{ isNewCharacter ? '创建角色' : '编辑角色' }}</h1>
          <div class="header-actions">
            <n-button @click="goBack">
              <template #icon><n-icon><ArrowBackOutline /></n-icon></template>
              返回
            </n-button>
            <n-button type="primary" @click="saveCharacter">
              <template #icon><n-icon><SaveOutline /></n-icon></template>
              保存
            </n-button>
          </div>
        </div>
      </template>
      
      <n-tabs type="line" animated>
        <n-tab-pane name="basic" tab="基本信息">
          <n-form
            ref="formRef"
            :model="characterForm"
            :rules="formRules"
            label-placement="left"
            label-width="100"
            require-mark-placement="right-hanging"
          >
            <n-form-item label="角色名称" path="name">
              <n-input v-model:value="characterForm.name" placeholder="请输入角色名称" />
            </n-form-item>
            
            <n-form-item label="标签" path="tags">
              <n-dynamic-tags v-model:value="characterForm.tags" />
            </n-form-item>
            
            <n-form-item label="缩略图" path="thumbnail">
              <n-upload
                action="#"
                :default-upload="false"
                :on-before-upload="beforeUploadThumbnail"
                accept="image/*"
                list-type="image-card"
                :max="1"
              >
                <div v-if="!characterForm.thumbnail">
                  <n-icon size="20">
                    <ImageOutline />
                  </n-icon>
                  <div>点击上传</div>
                </div>
                <img
                  v-else
                  :src="characterForm.thumbnail"
                  alt="缩略图"
                  style="max-width: 100%; max-height: 100%"
                />
              </n-upload>
            </n-form-item>
            
            <n-form-item label="物理效果" path="physicsEnabled">
              <n-switch v-model:value="characterForm.physicsEnabled" />
            </n-form-item>
          </n-form>
        </n-tab-pane>
        
        <n-tab-pane name="parts" tab="角色部件">
          <div class="parts-container">
            <div class="parts-list">
              <div class="parts-header">
                <h3>部件列表</h3>
                <n-button size="small" @click="addNewPart">
                  <template #icon><n-icon><AddOutline /></n-icon></template>
                  添加部件
                </n-button>
              </div>
              
              <n-list hoverable clickable>
                <n-list-item
                  v-for="part in characterForm.parts"
                  :key="part.id"
                  @click="selectPart(part)"
                  :class="{ 'active-part': selectedPart?.id === part.id }"
                >
                  <n-thing
                    :title="part.name"
                    :description="part.type"
                  >
                    <template #avatar>
                      <div class="part-thumbnail">
                        <img :src="part.imageUrl" :alt="part.name" />
                      </div>
                    </template>
                    <template #header-extra>
                      <n-space>
                        <n-button
                          quaternary
                          circle
                          size="small"
                          @click.stop="togglePartVisibility(part)"
                        >
                          <template #icon>
                            <n-icon>
                              <component :is="part.visible ? EyeOutline : EyeOffOutline" />
                            </n-icon>
                          </template>
                        </n-button>
                        <n-button
                          quaternary
                          circle
                          size="small"
                          @click.stop="deletePart(part)"
                        >
                          <template #icon><n-icon><TrashOutline /></n-icon></template>
                        </n-button>
                      </n-space>
                    </template>
                  </n-thing>
                </n-list-item>
              </n-list>
              
              <n-empty
                v-if="characterForm.parts.length === 0"
                description="暂无部件"
              >
                <template #extra>
                  <n-button @click="addNewPart">添加部件</n-button>
                </template>
              </n-empty>
            </div>
            
            <div class="part-editor" v-if="selectedPart">
              <h3>编辑部件: {{ selectedPart.name }}</h3>
              
              <n-form
                :model="selectedPart"
                label-placement="left"
                label-width="80"
              >
                <n-form-item label="名称">
                  <n-input v-model:value="selectedPart.name" />
                </n-form-item>
                
                <n-form-item label="类型">
                  <n-select
                    v-model:value="selectedPart.type"
                    :options="partTypeOptions"
                  />
                </n-form-item>
                
                <n-form-item label="图片">
                  <n-upload
                    action="#"
                    :default-upload="false"
                    :on-before-upload="(data) => beforeUploadPartImage(data, selectedPart)"
                    accept="image/*"
                    list-type="image-card"
                    :max="1"
                  >
                    <div v-if="!selectedPart.imageUrl">
                      <n-icon size="20">
                        <ImageOutline />
                      </n-icon>
                      <div>点击上传</div>
                    </div>
                    <img
                      v-else
                      :src="selectedPart.imageUrl"
                      alt="部件图片"
                      style="max-width: 100%; max-height: 100%"
                    />
                  </n-upload>
                </n-form-item>
                
                <n-form-item label="位置">
                  <n-input-group>
                    <n-input-number
                      v-model:value="selectedPart.position.x"
                      placeholder="X"
                      :step="1"
                    />
                    <n-input-number
                      v-model:value="selectedPart.position.y"
                      placeholder="Y"
                      :step="1"
                    />
                  </n-input-group>
                </n-form-item>
                
                <n-form-item label="旋转">
                  <n-input-number
                    v-model:value="selectedPart.rotation"
                    placeholder="度数"
                    :step="1"
                  />
                </n-form-item>
                
                <n-form-item label="缩放">
                  <n-input-group>
                    <n-input-number
                      v-model:value="selectedPart.scale.x"
                      placeholder="X"
                      :step="0.1"
                    />
                    <n-input-number
                      v-model:value="selectedPart.scale.y"
                      placeholder="Y"
                      :step="0.1"
                    />
                  </n-input-group>
                </n-form-item>
                
                <n-form-item label="透明度">
                  <n-slider
                    v-model:value="selectedPart.opacity"
                    :min="0"
                    :max="1"
                    :step="0.01"
                    :tooltip="true"
                    :format-tooltip="value => `${Math.round(value * 100)}%`"
                  />
                </n-form-item>
                
                <n-form-item label="Z轴顺序">
                  <n-input-number
                    v-model:value="selectedPart.zIndex"
                    placeholder="Z轴顺序"
                    :step="1"
                  />
                </n-form-item>
                
                <n-form-item label="翻转">
                  <n-space>
                    <n-checkbox v-model:checked="selectedPart.flipX">水平翻转</n-checkbox>
                    <n-checkbox v-model:checked="selectedPart.flipY">垂直翻转</n-checkbox>
                  </n-space>
                </n-form-item>
              </n-form>
            </div>
            
            <div class="part-editor-placeholder" v-else>
              <n-empty description="请选择一个部件进行编辑" />
            </div>
          </div>
        </n-tab-pane>
        
        <n-tab-pane name="skeleton" tab="骨骼系统">
          <div class="skeleton-container">
            <n-alert title="骨骼系统" type="info">
              骨骼系统功能正在开发中，敬请期待
            </n-alert>
            
            <!-- 骨骼系统编辑器将在此处实现 -->
            <div class="skeleton-editor-placeholder">
              <n-empty description="骨骼编辑器即将上线" />
            </div>
          </div>
        </n-tab-pane>
      </n-tabs>
    </n-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted, h } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useMessage } from 'naive-ui'
import { v4 as uuidv4 } from 'uuid'
import {
  NCard,
  NButton,
  NIcon,
  NTabs,
  NTabPane,
  NForm,
  NFormItem,
  NInput,
  NInputNumber,
  NInputGroup,
  NSelect,
  NSwitch,
  NSlider,
  NUpload,
  NList,
  NListItem,
  NThing,
  NSpace,
  NEmpty,
  NDynamicTags,
  NAlert,
  NCheckbox,
  FormInst
} from 'naive-ui'
import {
  ArrowBackOutline,
  SaveOutline,
  ImageOutline,
  AddOutline,
  TrashOutline,
  EyeOutline,
  EyeOffOutline
} from '@vicons/ionicons5'
import { useProjectStore } from '../../stores/projectStore'
import type { Character, CharacterPart, Vector2 } from '../../types/project'

const route = useRoute()
const router = useRouter()
const message = useMessage()
const projectStore = useProjectStore()

// 表单引用
const formRef = ref<FormInst | null>(null)

// 获取角色ID（如果是编辑模式）
const characterId = computed(() => route.params.id as string | undefined)
const projectId = computed(() => route.query.projectId as string)
const isNewCharacter = computed(() => !characterId.value)

// 选中的部件
const selectedPart = ref<CharacterPart | null>(null)

// 部件类型选项
const partTypeOptions = [
  { label: '头部', value: 'head' },
  { label: '身体', value: 'body' },
  { label: '手臂', value: 'arm' },
  { label: '腿部', value: 'leg' },
  { label: '装饰', value: 'decoration' },
  { label: '道具', value: 'prop' },
  { label: '其他', value: 'other' }
]

// 角色表单数据
const characterForm = reactive<Partial<Character>>({
  id: '',
  name: '',
  projectId: '',
  tags: [],
  parts: [],
  thumbnail: '',
  physicsEnabled: false,
  visible: true,
  locked: false,
  zIndex: 0,
  skeleton: {
    id: '',
    characterId: '',
    bones: [],
    rootBoneId: ''
  }
})

// 表单验证规则
const formRules = {
  name: {
    required: true,
    message: '请输入角色名称',
    trigger: 'blur'
  }
}

// 加载角色数据
const loadCharacter = async () => {
  if (characterId.value) {
    try {
      const result = await projectStore.fetchCharacter(characterId.value)
      if (result) {
        Object.assign(characterForm, result)
      } else {
        message.error('加载角色数据失败')
      }
    } catch (error) {
      console.error('加载角色数据错误:', error)
      message.error('加载角色数据时发生错误')
    }
  } else {
    // 新建角色，初始化默认值
    characterForm.id = uuidv4()
    characterForm.projectId = projectId.value
    characterForm.createdAt = new Date().toISOString()
    characterForm.updatedAt = new Date().toISOString()
    characterForm.parts = []
    characterForm.skeleton = {
      id: uuidv4(),
      characterId: characterForm.id,
      bones: [],
      rootBoneId: ''
    }
  }
}

// 保存角色
const saveCharacter = async () => {
  try {
    await formRef.value?.validate()
    
    characterForm.updatedAt = new Date().toISOString()
    
    const result = await projectStore.saveCharacter(characterForm as Character)
    if (result) {
      message.success('保存成功')
      if (isNewCharacter.value) {
        // 如果是新建，保存后跳转到编辑页面
        router.replace(`/character/edit/${result.id}?projectId=${projectId.value}`)
      }
    } else {
      message.error('保存失败')
    }
  } catch (error) {
    console.error('保存角色错误:', error)
    message.error('表单验证失败或保存时发生错误')
  }
}

// 返回上一页
const goBack = () => {
  router.back()
}

// 上传缩略图前处理
const beforeUploadThumbnail = (data: { file: File }) => {
  const reader = new FileReader()
  reader.onload = (e) => {
    characterForm.thumbnail = e.target?.result as string
  }
  reader.readAsDataURL(data.file)
  return false // 阻止默认上传行为
}

// 添加新部件
const addNewPart = () => {
  const newPart: CharacterPart = {
    id: uuidv4(),
    characterId: characterForm.id || '',
    type: 'body',
    name: `部件 ${characterForm.parts?.length ? characterForm.parts.length + 1 : 1}`,
    imageUrl: '',
    position: { x: 0, y: 0 },
    rotation: 0,
    scale: { x: 1, y: 1 },
    pivot: { x: 0.5, y: 0.5 },
    zIndex: characterForm.parts?.length || 0,
    visible: true,
    opacity: 1,
    flipX: false,
    flipY: false
  }
  
  characterForm.parts = characterForm.parts || []
  characterForm.parts.push(newPart)
  selectPart(newPart)
}

// 选择部件
const selectPart = (part: CharacterPart) => {
  selectedPart.value = part
}

// 切换部件可见性
const togglePartVisibility = (part: CharacterPart) => {
  part.visible = !part.visible
}

// 删除部件
const deletePart = (part: CharacterPart) => {
  if (!characterForm.parts) return
  
  const index = characterForm.parts.findIndex(p => p.id === part.id)
  if (index !== -1) {
    characterForm.parts.splice(index, 1)
    
    // 如果删除的是当前选中的部件，清除选择
    if (selectedPart.value?.id === part.id) {
      selectedPart.value = null
    }
  }
}

// 上传部件图片前处理
const beforeUploadPartImage = (data: { file: File }, part: CharacterPart) => {
  const reader = new FileReader()
  reader.onload = (e) => {
    part.imageUrl = e.target?.result as string
  }
  reader.readAsDataURL(data.file)
  return false // 阻止默认上传行为
}

// 初始化
onMounted(() => {
  loadCharacter()
})
</script>

<style lang="scss" scoped>
.character-editor-container {
  padding: 20px;
  height: 100%;
  overflow-y: auto;
  
  .character-editor-card {
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      
      h1 {
        margin: 0;
        font-size: 24px;
        font-weight: 500;
      }
      
      .header-actions {
        display: flex;
        gap: 12px;
      }
    }
  }
  
  .parts-container {
    display: grid;
    grid-template-columns: 300px 1fr;
    gap: 20px;
    margin-top: 20px;
    
    .parts-list {
      border-right: 1px solid var(--divider-color);
      padding-right: 20px;
      
      .parts-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 16px;
        
        h3 {
          margin: 0;
        }
      }
      
      .active-part {
        background-color: var(--primary-color-hover);
      }
      
      .part-thumbnail {
        width: 40px;
        height: 40px;
        display: flex;
        align-items: center;
        justify-content: center;
        overflow: hidden;
        border-radius: 4px;
        background-color: var(--card-color);
        
        img {
          max-width: 100%;
          max-height: 100%;
          object-fit: contain;
        }
      }
    }
    
    .part-editor,
    .part-editor-placeholder {
      padding-left: 20px;
      
      h3 {
        margin-top: 0;
        margin-bottom: 16px;
      }
    }
  }
  
  .skeleton-container {
    margin-top: 20px;
    
    .skeleton-editor-placeholder {
      margin-top: 40px;
      display: flex;
      justify-content: center;
    }
  }
}

/* 响应式调整 */
@media (max-width: 768px) {
  .character-editor-container {
    padding: 10px;
    
    .parts-container {
      grid-template-columns: 1fr;
      
      .parts-list {
        border-right: none;
        border-bottom: 1px solid var(--divider-color);
        padding-right: 0;
        padding-bottom: 20px;
      }
      
      .part-editor,
      .part-editor-placeholder {
        padding-left: 0;
        padding-top: 20px;
      }
    }
  }
}
</style> 